package com.example.hospitalsystemclient.ui.notifications;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.hospitalsystemclient.Dataclass.RegShortInfo;
import com.example.hospitalsystemclient.Dataclass.UrlData;
import com.example.hospitalsystemclient.R;
import com.example.hospitalsystemclient.databinding.FragmentNotificationsBinding;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class NotificationsFragment extends Fragment {

    private FragmentNotificationsBinding binding;
    private UrlData urlData = new UrlData();
    private List<RegShortInfo> regList = new ArrayList<>();
    private RegAdapter regAdapter;
    private RecyclerView recyclerView;
    private RegShortInfo curReg;
    private ConstraintLayout inNoneLayout;
    private ConstraintLayout notNoneLayout;
    private TextView notNoneTitle;
    private Button payRegButton;
    private Button cancelRegButton;
    private Button payPreButton;
    private Button payCheckButton;
    private TextView queueInfoText;
    private TextView beLockText;

    private Integer curPreId = -1;
    private Integer curCheckListId = -1;

    private Handler handler = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            handler.postDelayed(this, 5000);
            // 在这里执行刷新数据的代码
            flash();

            // 重新安排 Runnable，使其每 10 秒执行一次
        }
    };

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        NotificationsViewModel notificationsViewModel =
                new ViewModelProvider(this).get(NotificationsViewModel.class);

        binding = FragmentNotificationsBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        flash();

        recyclerView = binding.regListView;
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        regAdapter = new RegAdapter(regList);
        recyclerView.setAdapter(regAdapter);

        inNoneLayout = binding.none;
        notNoneLayout = binding.notNone;
        notNoneTitle = binding.notNoneTitle;
        payRegButton = binding.payReg;
        cancelRegButton = binding.cancelReg;
        payPreButton = binding.preButton;
        payCheckButton = binding.checkButton;
        queueInfoText = binding.queueInfo;
        beLockText = binding.beLockNotice;

        initialButtons();

        handler.post(runnable);

        return root;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        handler.removeCallbacks(runnable);
        binding = null;
    }

    private void flash() {
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("localData", 0);
        Integer patientId = sharedPreferences.getInt("patientId", -1);

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("patientId", patientId.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());

        Request request = new Request.Builder()
                .url(urlData.showUndoList())
                .post(requestBody)
                .build();

        OkHttpClient client = new OkHttpClient();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                if(isAdded()) requireActivity().runOnUiThread(() -> Toast.makeText(requireContext(), "网络问题", Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    final String responseData = response.body().string();
                    try {
                        JSONObject jsonObject = new JSONObject(responseData);
                        if (jsonObject.getBoolean("stat")) {
                            JSONArray dataArray = jsonObject.getJSONArray("datas");
                            regList.clear();

                            for (int i = 0; i < dataArray.length(); i++) {
                                JSONObject regItem = dataArray.getJSONObject(i);

                                RegShortInfo regShortInfo = new RegShortInfo();
                                regShortInfo.setRegId(regItem.getInt("regId"));
                                regShortInfo.setState(regItem.getInt("state"));
                                regShortInfo.setQueueNumber(regItem.getInt("queueNumber"));
                                regShortInfo.setOfficeName(regItem.getString("officeName"));
                                regShortInfo.setDocName(regItem.getString("docName"));
                                regShortInfo.setRegTime(regItem.getString("regTime"));
                                regShortInfo.setAppointmentTime(regItem.getString("appointmentTime"));
                                regShortInfo.setPrice(regItem.getInt("docPrice"));

                                regList.add(regShortInfo);

                            }

                            boolean isGetCur = false;

                            for (int i = 0; i < regList.size(); i++) {
                                RegShortInfo regShortInfo = regList.get(i);
                                if (regShortInfo.getState() == 4) {
                                    curReg = regShortInfo;
                                    isGetCur = true;
                                    getRegDetail();
                                    inDo();
                                    break;
                                }
                            }

                            if (!isGetCur) {
                                for (int i = 0; i < regList.size(); i++) {
                                    RegShortInfo regShortInfo = regList.get(i);
                                    if (regShortInfo.getState() == 3) {
                                        curReg = regShortInfo;
                                        isGetCur = true;
                                        beLock();
                                        break;
                                    }
                                }
                            }

                            if (!isGetCur) {
                                for (int i = 0; i < regList.size(); i++) {
                                    RegShortInfo regShortInfo = regList.get(i);
                                    if (regShortInfo.getState() == 2) {
                                        curReg = regShortInfo;
                                        isGetCur = true;
                                        inQueue();
                                        break;
                                    }
                                }
                            }

                            Long curTime = new Date().getTime();
                            if (!isGetCur) {
                                for (int i = 0; i < regList.size(); i++) {
                                    RegShortInfo regShortInfo = regList.get(i);
                                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    try {
                                        Long appointTime = simpleDateFormat.parse(regShortInfo.getAppointmentTime()).getTime();
                                        Long timeDiff = appointTime - curTime;
                                        if (regShortInfo.getState() == 0 && timeDiff > 0 && timeDiff <= 1200000) {
                                            curReg = regShortInfo;
                                            isGetCur = true;
                                            inPay();
                                            break;
                                        }
                                    } catch (ParseException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }

                            if (!isGetCur) inNone();

                            if(isAdded()){
                                requireActivity().runOnUiThread(() -> {
                                    // 更新 UI
                                    if(regList.size() != 0){
                                        for(int i=0;i<regList.size();i++){
                                            if(curReg.getRegId().equals(regList.get(i).getRegId())){
//                                                if(i<regList.size()) regList.remove(i);
                                                break;
                                            }
                                        }
                                    }
                                    regAdapter.updateRegList(regList);
                                });
                            }

                        } else {
                            requireActivity().runOnUiThread(() -> Toast.makeText(requireContext(), "未知错误", Toast.LENGTH_SHORT).show());
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    requireActivity().runOnUiThread(() -> Toast.makeText(requireContext(), "未知错误", Toast.LENGTH_SHORT).show());
                }
            }
        });
    }

    private void inPay() {
        if(isAdded()){
            requireActivity().runOnUiThread(() -> {
                turnDownALl(420);
                notNoneLayout.setVisibility(View.VISIBLE);
                notNoneLayout.setBackground(getResources().getDrawable(R.drawable.in_pay_bg));
                payRegButton.setVisibility(View.VISIBLE);
                cancelRegButton.setVisibility(View.VISIBLE);
                showCurRegInfo();
                notNoneTitle.setText("可缴费");
            });
        }
    }

    private void beLock() {
        if(isAdded()){
            requireActivity().runOnUiThread(() -> {
                turnDownALl(420);
                notNoneLayout.setVisibility(View.VISIBLE);
                notNoneLayout.setBackground(getResources().getDrawable(R.drawable.be_lock_bg));
                beLockText.setVisibility(View.VISIBLE);
                showCurRegInfo();
                notNoneTitle.setText("被挂起");
            });
        }
    }

    private void inQueue() {
        if(isAdded()){
            requireActivity().runOnUiThread(() -> {
                turnDownALl(420);
                notNoneLayout.setVisibility(View.VISIBLE);
                notNoneLayout.setBackground(getResources().getDrawable(R.drawable.in_queue_bg));
                queueInfoText.setVisibility(View.VISIBLE);
                showCurRegInfo();
                notNoneTitle.setText("正在排队");

                queueInfoText.setText("你的队列前方还有"+String.valueOf(curReg.getQueueNumber())+"人");
            });
        }
    }

    private void inDo() {
        if(isAdded()){
            requireActivity().runOnUiThread(() -> {
                turnDownALl(420);
                notNoneLayout.setVisibility(View.VISIBLE);
                notNoneLayout.setBackground(getResources().getDrawable(R.drawable.in_doing_bg));
                payPreButton.setVisibility(View.VISIBLE);
                payCheckButton.setVisibility(View.VISIBLE);
                showCurRegInfo();
                notNoneTitle.setText("正在就诊");
            });
        }
    }

    private void inNone() {
        if(isAdded()){
            requireActivity().runOnUiThread(() -> {
                turnDownALl(550);
                inNoneLayout.setVisibility(View.VISIBLE);
            });
        }
    }

    private void turnDownALl(int heightInDp) {//长的550，短的420，差130
        inNoneLayout.setVisibility(View.INVISIBLE);
        notNoneLayout.setVisibility(View.INVISIBLE);
        payRegButton.setVisibility(View.INVISIBLE);
        cancelRegButton.setVisibility(View.INVISIBLE);
        payPreButton.setVisibility(View.INVISIBLE);
        payCheckButton.setVisibility(View.INVISIBLE);
        queueInfoText.setVisibility(View.INVISIBLE);
        beLockText.setVisibility(View.INVISIBLE);

        ConstraintLayout.LayoutParams RLayoutParams = (ConstraintLayout.LayoutParams) recyclerView.getLayoutParams();
        int heightInPixels = (int) (heightInDp * getResources().getDisplayMetrics().density);
        RLayoutParams.height = heightInPixels;
        recyclerView.setLayoutParams(RLayoutParams);
    }

    private void getRegDetail(){
        OkHttpClient client = new OkHttpClient();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("regId", curReg.getRegId());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());
        Request request = new Request.Builder()
                .url(urlData.getRegDetail())
                .post(requestBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                requireActivity().runOnUiThread(() -> Toast.makeText(requireContext(), "网络问题", Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if(response.isSuccessful()){
                    final String responseData = response.body().string();
                    try {
                        JSONObject jsonObject = new JSONObject(responseData);
                        JSONObject datasObject = null;
                        try {
                            datasObject = jsonObject.getJSONObject("datas");
                        }catch (JSONException ignored) {
                        }
                        if (jsonObject.getBoolean("stat") && datasObject != null) {
                            curPreId = -1;
                            curCheckListId = -1;
                            curPreId = datasObject.getInt("prescriptionId");
                            curCheckListId = datasObject.getInt("checklistId");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    if(isAdded()) requireActivity().runOnUiThread(() -> Toast.makeText(requireContext(), "错误！", Toast.LENGTH_SHORT).show());
                }
            }
        });
    }

    private void showCurRegInfo(){
        TextView tvRegId = binding.tvRegId;
        TextView tvDocName = binding.tvDocName;
        TextView tvPrice = binding.tvPrice;
        TextView tvOffice = binding.tvOffice;
        TextView tvAppointTime = binding.tvAppointTime;

        tvRegId.setText("编号:"+String.valueOf(curReg.getRegId()));
        tvDocName.setText("主治医生:"+curReg.getDocName());
        tvPrice.setText("挂号费："+String.valueOf(curReg.getPrice())+"元");
        tvOffice.setText("科室："+curReg.getOfficeName());
        tvAppointTime.setText("预约时间："+curReg.getAppointmentTime());
    }

    private void initialButtons() {
        payRegButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                OkHttpClient client = new OkHttpClient();
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("regId", curReg.getRegId().toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());
                Request request = new Request.Builder()
                        .url(urlData.payReg())
                        .post(requestBody)
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        requireActivity().runOnUiThread(() -> Toast.makeText(requireContext(), "网络问题", Toast.LENGTH_SHORT).show());
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        if(response.isSuccessful()){
                            final String responseData = response.body().string();
                            try {
                                JSONObject jsonObject = new JSONObject(responseData);
                                if (jsonObject.getBoolean("stat")) {
                                    requireActivity().runOnUiThread(() -> Toast.makeText(requireContext(), "支付成功", Toast.LENGTH_SHORT).show());
                                    flash();
                                } else {
                                    requireActivity().runOnUiThread(() -> Toast.makeText(requireContext(), "支付失败", Toast.LENGTH_SHORT).show());
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        } else {
                            requireActivity().runOnUiThread(() -> Toast.makeText(requireContext(), "错误！", Toast.LENGTH_SHORT).show());
                        }
                    }
                });
            }
        });

        //------------------------------------------------------------------------------
        cancelRegButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                OkHttpClient client = new OkHttpClient();
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("regId", curReg.getRegId().toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());
                Request request = new Request.Builder()
                        .url(urlData.cancelReg())
                        .post(requestBody)
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        requireActivity().runOnUiThread(() -> Toast.makeText(requireContext(), "网络问题", Toast.LENGTH_SHORT).show());
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        if(response.isSuccessful()){
                            final String responseData = response.body().string();
                            try {
                                JSONObject jsonObject = new JSONObject(responseData);
                                if (jsonObject.getBoolean("stat")) {
                                    requireActivity().runOnUiThread(() -> Toast.makeText(requireContext(), "已取消", Toast.LENGTH_SHORT).show());
                                    flash();
                                } else {
                                    requireActivity().runOnUiThread(() -> Toast.makeText(requireContext(), "支付失败", Toast.LENGTH_SHORT).show());
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            requireActivity().runOnUiThread(() -> Toast.makeText(requireContext(), "错误！", Toast.LENGTH_SHORT).show());
                        }
                    }
                });
            }
        });
        //----------------------------------------------------------------
        payPreButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(curPreId != -1){
                    SharedPreferences sharedPreferences = requireContext().getSharedPreferences("preInfo", 0);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putInt("preId", curPreId);
                    editor.apply();

                    if (isAdded()){
                        requireActivity().runOnUiThread(() -> {
                            // 跳转到医生详细信息 Fragment
                            NavController navController = Navigation.findNavController(requireActivity(), R.id.nav_host_fragment_activity_main);
                            navController.navigate(R.id.preInfoFragment);
                        });
                    }
                } else {
                    if (isAdded()) requireActivity().runOnUiThread(() -> Toast.makeText(requireContext(), "未开具处方单", Toast.LENGTH_SHORT).show());
                }
            }
        });

        payCheckButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(curPreId != -1){
                    SharedPreferences sharedPreferences = requireContext().getSharedPreferences("checkListInfo", 0);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putInt("checkListId", curCheckListId);
                    editor.apply();

                    if (isAdded()){
                        requireActivity().runOnUiThread(() -> {
                            // 跳转到医生详细信息 Fragment
                            NavController navController = Navigation.findNavController(requireActivity(), R.id.nav_host_fragment_activity_main);
                            navController.navigate(R.id.checkInfoFragment);
                        });
                    }
                } else {
                    if (isAdded()) requireActivity().runOnUiThread(() -> Toast.makeText(requireContext(), "未开具检查单", Toast.LENGTH_SHORT).show());
                }
            }
        });
    }
}